// 引入配置文件
document.write('<script src="js/config.js"></script>');

$(document).ready(function() {
    // 检查是否已登录
    if (!checkAuth()) return;
    
    // 初始化变量
    let currentBookId = null;
    let isEditing = false;
    let booksKeyword = '';
    
    // 显示用户信息
    const userInfo = getUserInfo();
    $('#username').text(userInfo.username);
    
    // 初始化加载数据
    loadBooks();
    
    // 退出登录
    $('#logout-btn').click(function() {
        removeToken();
        removeUserInfo();
        window.location.href = 'index.html';
    });
    
    // 新建图书按钮点击
    $('#new-book-btn').click(function() {
        openBookModal();
    });
    
    // 取消按钮点击
    $('#cancel-btn').click(function() {
        closeBookModal();
    });
    
    // 模态框关闭按钮点击
    $('.close').click(function() {
        closeBookModal();
        closeViewBookModal();
    });
    
    // 图书表单提交
    $('#book-form').submit(function(e) {
        e.preventDefault();
        
        const bookId = $('#book-id').val();
        const title = $('#book-title').val().trim();
        const author = $('#book-author').val().trim();
        const isbn = $('#book-isbn').val().trim();
        const description = $('#book-description').val().trim();
        const quantity = parseInt($('#book-quantity').val());
        
        if (!title) {
            alert('标题不能为空');
            return;
        }
        
        if (!author) {
            alert('作者不能为空');
            return;
        }
        
        if (!isbn) {
            alert('ISBN不能为空');
            return;
        }
        
        if (isNaN(quantity) || quantity < 0) {
            alert('数量必须是非负整数');
            return;
        }
        
        const bookData = {
            title,
            author,
            isbn,
            description,
            quantity
        };
        
        let apiUrl, method;
        
        if (isEditing && bookId) {
            // 更新图书
            apiUrl = `/books/updateBook/${bookId}`;
            method = 'PUT';
        } else {
            // 创建图书
            apiUrl = '/books/createBook';
            method = 'POST';
        }
        
        apiRequest(apiUrl, method, bookData)
            .then(data => {
                closeBookModal();
                loadBooks();
                alert(isEditing ? '图书更新成功' : '图书创建成功');
            })
            .catch(error => {
                alert(error.message || '操作失败，请稍后再试');
            });
    });
    
    // 图书搜索
    $('#books-search-btn').click(function() {
        booksKeyword = $('#books-search').val().trim().toLowerCase();
        loadBooks();
    });
    
    // 编辑图书按钮点击
    $(document).on('click', '#edit-book-btn', function() {
        const bookId = $(this).data('id');
        
        apiRequest(`/books/getBookById/${bookId}`, 'GET')
            .then(book => {
                closeViewBookModal();
                openBookModal(book);
            })
            .catch(error => {
                alert(error.message || '获取图书详情失败');
            });
    });
    
    // 删除图书按钮点击
    $(document).on('click', '#delete-book-btn', function() {
        const bookId = $(this).data('id');
        
        if (confirm('确定要删除这本图书吗？此操作不可恢复。')) {
            apiRequest(`/books/deleteBook/${bookId}`, 'DELETE')
                .then(data => {
                    closeViewBookModal();
                    loadBooks();
                    alert('图书删除成功');
                })
                .catch(error => {
                    alert(error.message || '删除失败，请稍后再试');
                });
        }
    });
    
    // 点击图书项查看详情
    $(document).on('click', '.book-item', function() {
        const bookId = $(this).data('id');
        
        apiRequest(`/books/getBookById/${bookId}`, 'GET')
            .then(book => {
                openViewBookModal(book);
            })
            .catch(error => {
                alert(error.message || '获取图书详情失败');
            });
    });
    
    // 加载图书列表
    function loadBooks() {
        apiRequest('/books/getAllBooks', 'GET')
            .then(response => {
                // 如果有搜索关键词，进行本地过滤
                if (booksKeyword) {
                    const keyword = booksKeyword.toLowerCase();
                    response = response.filter(book => 
                        book.title.toLowerCase().includes(keyword) ||
                        book.author.toLowerCase().includes(keyword) ||
                        book.isbn.toLowerCase().includes(keyword)
                    );
                }
                renderBooksList(response);
            })
            .catch(error => {
                console.error('加载图书列表失败:', error);
                $('#books-list').html(`<div class="error-message">加载失败: ${error.message}</div>`);
            });
    }
    
    // 渲染图书列表
    function renderBooksList(books) {
        const $container = $('#books-list');
        
        if (!books || books.length === 0) {
            $container.html('<div class="empty-message">暂无图书</div>');
            return;
        }
        
        let html = '';
        
        books.forEach(book => {
            html += `
                <div class="book-item" data-id="${book.id}">
                    <h3>${book.title}</h3>
                    <p class="book-author">作者: ${book.author}</p>
                    <p class="book-isbn">ISBN: ${book.isbn}</p>
                    <p class="book-preview">${truncateText(book.description, 100)}</p>
                    <div class="book-meta">
                        <span>库存: ${book.quantity}</span>
                    </div>
                </div>
            `;
        });
        
        $container.html(html);
    }
    
    // 打开图书编辑模态框
    function openBookModal(book = null) {
        // 重置表单
        $('#book-form')[0].reset();
        $('#book-id').val('');
        
        if (book) {
            // 编辑模式
            $('#modal-title').text('编辑图书');
            $('#book-id').val(book.id);
            $('#book-title').val(book.title);
            $('#book-author').val(book.author);
            $('#book-isbn').val(book.isbn);
            $('#book-description').val(book.description);
            $('#book-quantity').val(book.quantity);
            
            currentBookId = book.id;
            isEditing = true;
        } else {
            // 新建模式
            $('#modal-title').text('新建图书');
            currentBookId = null;
            isEditing = false;
        }
        
        $('#book-modal').css('display', 'block');
    }
    
    // 关闭图书编辑模态框
    function closeBookModal() {
        $('#book-modal').css('display', 'none');
    }
    
    // 打开图书查看模态框
    function openViewBookModal(book) {
        $('#view-book-title').text(book.title);
        $('#view-book-author').text(book.author);
        $('#view-book-isbn').text(book.isbn);
        $('#view-book-description').text(book.description);
        $('#view-book-quantity').text(book.quantity);
        
        // 设置操作按钮
        $('#view-book-actions').show();
        $('#edit-book-btn').data('id', book.id);
        $('#delete-book-btn').data('id', book.id);
        
        $('#view-book-modal').css('display', 'block');
    }
    
    // 关闭图书查看模态框
    function closeViewBookModal() {
        $('#view-book-modal').css('display', 'none');
    }
    
    // 文本截断函数
    function truncateText(text, maxLength) {
        if (!text) return '';
        if (text.length <= maxLength) return text;
        return text.substring(0, maxLength) + '...';
    }
}); 